package com.dongnao.network.netty_packet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

public class NettyClientHandler2 extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    //与服务器通道就绪触发方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        for (int i = 0; i < 5; i++) {
            String msg = "今天天气冷，我想吃火锅" + i;
            byte[] bytes = msg.getBytes(Charset.forName("utf-8"));
            int length = bytes.length;

            //创建协议包对象
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(bytes);

            ctx.writeAndFlush(messageProtocol);
        }
    }

    //通道有读取事件发生触发
    @Override
    public void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) {
        System.out.println("客户端接收到消息=" + new String(msg.getContent(), CharsetUtil.UTF_8));
        System.out.println("客户端接收消息数量=" + (++this.count));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
